package com.turing.post.organization.impl;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.MerchantCardFee;
import com.turing.post.organization.util.MerchantFeePolicy;
import com.turing.post.organization.util.MerchantFeePolicyBusiness;
import com.turing.post.organization.util.MerchantFeePolicyDao;
import com.turing.post.organization.util.OrganApplicationException;
import com.turing.post.organization.util.OrganRespCode;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

@Stateless(mappedName = "organization.impl.MerchantFeePolicyBusinessImpl")
@Remote
@Local
public class MerchantFeePolicyBusinessImpl implements MerchantFeePolicyBusiness {

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;
	@EJB(mappedName = "organization.impl.MerchantFeePolicyDaoImpl")
	private MerchantFeePolicyDao merchantFeePolicyDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao activateCardDaoImpl;

	@EJB(mappedName = "	common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;

	@Override
	public MerchantCardFee calcCardHolderFee(String merchantNo,
			String mrchBranchNo, Date tranDate, String tranType,
			String businessType, String cardNo, BigInteger amount) {

		MerchantCardFee mcf = new MerchantCardFee();
		mcf.feeRatio = mcf.fee = BigInteger.ZERO;

		ActivateCard ac = activateCardDaoImpl.getActivateCardByCardNo(cardNo);
		if (ac == null)
			return mcf;

		MerchantFeePolicy mfp = new MerchantFeePolicy();

		mfp.setMerchantNo(merchantNo);
		mfp.setMrchBranchNo(mrchBranchNo);
		mfp.setTranType(tranType);
		mfp.setBusinessType(businessType);
		mfp.setStartDate(tranDate);
		mfp.setCardFaceId(ac.getCardFaceId());
		mfp.setCardClassicId(ac.getCardClassicId());
		mfp.setStartCardSeqNo(ac.getCardSeqNo());
		mfp.setStartAmount(amount);

		List<MerchantFeePolicy> mfplist = merchantFeePolicyDaoImpl
				.getMerchantFeePolicyByBusiness(mfp);
		if (mfplist == null || mfplist.size() < 1)
			return mcf;

		MerchantFeePolicy curmfp = null;
		int curmfpscore = 0;
		int score = 0;

		// 评估策略的优先级,匹配多者优先
		for (MerchantFeePolicy lmfp : mfplist) {
			score = 0;

			// 商户分支机构匹配上+1
			if (PCPSUtil.compareObject(lmfp.getMrchBranchNo(), mrchBranchNo))
				score++;

			// 业务类型匹配上+1
			if (PCPSUtil.compareObject(lmfp.getBusinessType(), businessType))
				score++;

			// 卡面匹配上+1
			if (PCPSUtil
					.compareObject(lmfp.getCardFaceId(), ac.getCardFaceId()))
				score++;

			// 卡种类匹配上+1
			if (PCPSUtil.compareObject(lmfp.getCardClassicId(), ac
					.getCardClassicId()))
				score++;

			// 卡序号范围完全匹配上+3,匹配上1个+1
			if (!PCPSUtil.isEmpty(lmfp.getStartCardSeqNo())
					&& !PCPSUtil.isEmpty(lmfp.getEndCardSeqNo()))
				score += 3;
			else if (PCPSUtil.isEmpty(lmfp.getStartCardSeqNo())
					&& PCPSUtil.isEmpty(lmfp.getEndCardSeqNo()))
				score += 0;
			else
				score++;

			// 日期范围完全匹配上+3,匹配上1个+1
			if (lmfp.getStartDate() != null && lmfp.getEndDate() != null)
				score += 3;
			else if (lmfp.getStartDate() == null && lmfp.getEndDate() == null)
				score += 0;
			else
				score++;

			// 金额范围完全匹配上+3,匹配上1个+1
			if (BigInteger.ZERO.compareTo(lmfp.getStartAmount()) < 0
					&& BigInteger.ZERO.compareTo(lmfp.getEndAmount()) < 0)
				score += 3;
			else if (BigInteger.ZERO.compareTo(lmfp.getStartAmount()) >= 0
					&& BigInteger.ZERO.compareTo(lmfp.getEndAmount()) >= 0)
				score += 0;
			else
				score++;

			if (score > curmfpscore || curmfp == null) {
				curmfp = lmfp;
				curmfpscore = score;
			}
		}

		// 策略ID
		mcf.policyId = curmfp.getMrchFeePolicyId();

		// 固定费率
		if (PCPSUtil.compareObject(curmfp.getFeeType(),
				MerchantFeePolicy.FEETYPE_FIX))
			mcf.fee = curmfp.getFixFee();
		else if (PCPSUtil.compareObject(curmfp.getFeeType(),
				MerchantFeePolicy.FEETYPE_FEERATIO)) {
			mcf.fee = PCPSUtil.calcFee(curmfp.getFixRatio(), amount);
			// 费率始终返回非负
			mcf.feeRatio = curmfp.getFixRatio().abs();
		}

		return mcf;
	}

	@Override
	public void insertMerchantFeePolicy(PCPSWebInput webInput,
			MerchantFeePolicy mfp) throws PCPSApplicationException {
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| webInput.getOperId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"登录操作员归属机构号为空!");
		}
		if (PCPSUtil.isEmpty(mfp.getMerchantNo())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"商户号为空！");
		}
		if (PCPSUtil.isEmpty(mfp.getTranType())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"交易类型为空！");
		}
		if (mfp.getStartAmount() == null) {
			mfp.setStartAmount(BigInteger.ZERO);
		}
		if (mfp.getEndAmount() == null) {
			mfp.setEndAmount(BigInteger.ZERO);
		}
		if (PCPSUtil.isEmpty(mfp.getFeeType())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"消费折扣为空！");
		}
		if (mfp.getFixRatio() == null) {
			mfp.setFixRatio(BigInteger.ZERO);
		}
		if (mfp.getFixFee() == null) {
			mfp.setFixFee(BigInteger.ZERO);
		}
		mfp.setMrchFeePolicyId(commonDaoImpl.getUniqueIntegerKey());
		mfp.setCreateOperId(webInput.getOperId());
		mfp.setCreateTime(commonDaoImpl.getDatabaseSysTime());
		mfp.setStatus(MerchantFeePolicy.STATUS_VALID_WAIT_AUTH);
		merchantFeePolicyDaoImpl.insert(mfp);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Add, "新增持卡人商户交易折扣/手续费", "商户号："
						+ mfp.getMerchantNo() + "商户机构号："
						+ mfp.getMrchBranchNo());
	}

	@Override
	public void updateMerchantFeePolicy(PCPSWebInput webInput,
			MerchantFeePolicy mfp) throws PCPSApplicationException {
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| webInput.getOperId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"登录操作员归属机构号为空!");
		}
		if (mfp.getMrchFeePolicyId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"资费策略编号为空！");
		}
		if (PCPSUtil.isEmpty(mfp.getMerchantNo())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"商户号为空！");
		}
		if (PCPSUtil.isEmpty(mfp.getTranType())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"交易类型为空！");
		}
		if (PCPSUtil.isEmpty(mfp.getFeeType())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"消费折扣为空！");
		}

		MerchantFeePolicy mfpupdate = merchantFeePolicyDaoImpl
				.getMerchantFeePolicyByPolicyIdForUpdate(mfp
						.getMrchFeePolicyId());
		if (mfpupdate == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"待修改持卡人商户交易资费策略为空！");
		}
		mfpupdate.setMerchantNo(mfp.getMerchantNo());
		mfpupdate.setTranType(mfp.getTranType());
		mfpupdate.setBusinessType(mfp.getBusinessType());
		mfpupdate.setMrchBranchNo(mfp.getMrchBranchNo());
		mfpupdate.setCardFaceId(mfp.getCardFaceId());
		mfpupdate.setCardClassicId(mfp.getCardClassicId());
		mfpupdate.setStartCardSeqNo(mfp.getStartCardSeqNo());
		mfpupdate.setEndCardSeqNo(mfp.getEndCardSeqNo());
		mfpupdate.setStartDate(mfp.getStartDate());
		mfpupdate.setEndDate(mfp.getEndDate());
		if (mfp.getStartAmount() == null) {
			mfpupdate.setStartAmount(BigInteger.ZERO);
		}
		if (mfp.getEndAmount() == null) {
			mfpupdate.setEndAmount(BigInteger.ZERO);
		}
		mfpupdate.setFeeType(mfp.getFeeType());
		if (mfp.getFixRatio() == null) {
			mfpupdate.setFixRatio(BigInteger.ZERO);
		} else {
			mfpupdate.setFixRatio(mfp.getFixRatio());
		}
		if (mfp.getFixFee() == null) {
			mfpupdate.setFixFee(BigInteger.ZERO);
		} else {
			mfpupdate.setFixFee(mfp.getFixFee());
		}
		mfpupdate.setStatus(mfp.getStatus());
		mfpupdate.setRemark(mfp.getRemark());
		merchantFeePolicyDaoImpl.update(mfpupdate);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Edit, "修改持卡人商户交易折扣/手续费", "商户号："
						+ mfp.getMerchantNo() + "商户机构号："
						+ mfp.getMrchBranchNo());
	}

	@Override
	public void deleteMerchantFeePolicy(PCPSWebInput webInput,
			BigInteger mrchFeePolicyId) throws PCPSApplicationException {
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| webInput.getOperId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"登录操作员归属机构号为空!");
		}
		if (mrchFeePolicyId == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"资费策略编号为空！");
		}
		MerchantFeePolicy mfp = merchantFeePolicyDaoImpl
				.getMerchantFeePolicyByPolicyIdForUpdate(mrchFeePolicyId);
		if (mfp == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"待删除持卡人商户交易资费策略为空！");
		}
		if (!mfp.getStatus().equals(MerchantFeePolicy.STATUS_VALID_WAIT_AUTH)) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"待删除持卡人商户交易资费策略状态不正确！");
		}
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Delete, "删除持卡人商户交易折扣/手续费", "商户号："
						+ mfp.getMerchantNo() + "商户机构号："
						+ mfp.getMrchBranchNo());
		merchantFeePolicyDaoImpl.delete(mfp);
	}
	//通过
	@Override
	public void authMerchantFeePolicy(PCPSWebInput webInput,
			BigInteger mrchFeePolicyId) throws PCPSApplicationException {
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| webInput.getOperId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"登录操作员归属机构号为空!");
		}
		if (mrchFeePolicyId == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"资费策略编号为空!");
		}
		MerchantFeePolicy mfp = merchantFeePolicyDaoImpl
				.getMerchantFeePolicyByPolicyIdForUpdate(mrchFeePolicyId);
		if (mfp == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"待审核的持卡人商户交易资费策略为空!");
		}
		if (mfp.getStatus().equals(MerchantFeePolicy.STATUS_VALID)
				|| mfp.getStatus().equals(MerchantFeePolicy.STATUS_INVALID)) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"待审核的商户交易资费策略状态不正确!");
		}
		if (mfp.getStatus().equals(MerchantFeePolicy.STATUS_VALID_WAIT_AUTH)) {
			if (mfp.getCreateOperId().compareTo(webInput.getOperId()) == 0) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "商户交易资费策略审核人不可为创建人!");
			}
			// 生效待审核-->生效
			mfp.setStatus(MerchantFeePolicy.STATUS_VALID);
		} else if (mfp.getStatus().equals(
				MerchantFeePolicy.STATUS_INVALID_WAIT_AUTH)) {
			if (mfp.getAuthOperId().compareTo(webInput.getOperId()) == 0) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "商户交易资费策略审核人不能为申请人!");
			}
			// 无效待审核-->无效
			mfp.setStatus(MerchantFeePolicy.STATUS_INVALID);
		}
		mfp.setAuthOperId(webInput.getOperId());
		mfp.setAuthTime(commonDaoImpl.getDatabaseSysTime());
		merchantFeePolicyDaoImpl.update(mfp);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Edit, "审核通过商户交易折扣/手续费", "商户号："
						+ mfp.getMerchantNo() + "商户机构号："
						+ mfp.getMrchBranchNo());
	}
	//无效
	@Override
	public void closeMerchantFeePolicy(PCPSWebInput webInput,
			BigInteger mrchFeePolicyId) throws PCPSApplicationException {
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| webInput.getOperId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"登录操作员归属机构号为空!");
		}
		if (mrchFeePolicyId == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"资费策略编号为空!");
		}
		MerchantFeePolicy mfp = merchantFeePolicyDaoImpl
				.getMerchantFeePolicyByPolicyIdForUpdate(mrchFeePolicyId);
		if (mfp == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"商户交易资费策略为空!");
		}
		if (!mfp.getStatus().equals(MerchantFeePolicy.STATUS_VALID)) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"商户交易资费策略状态不正确!");
		}
		// 生效-->无效待审核
		mfp.setStatus(MerchantFeePolicy.STATUS_INVALID_WAIT_AUTH);
		mfp.setAuthOperId(webInput.getOperId());
		merchantFeePolicyDaoImpl.update(mfp);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Edit, "商户交易折扣/手续费设置无效", "商户号："
						+ mfp.getMerchantNo() + "商户机构号："
						+ mfp.getMrchBranchNo() + "手续费类型：" + mfp.getFeeType());
	}
	//拒绝
	@Override
	public void unAuthMerchantFeePolicy(PCPSWebInput webInput,
			BigInteger mrchFeePolicyId) throws PCPSApplicationException {
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| webInput.getOperId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"登录操作员归属机构号为空!");
		}
		if (mrchFeePolicyId == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"资费策略编号为空!");
		}
		MerchantFeePolicy mfp = merchantFeePolicyDaoImpl
				.getMerchantFeePolicyByPolicyIdForUpdate(mrchFeePolicyId);
		if (mfp == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"待审核的商户交易资费策略为空!");
		}
		if (mfp.getStatus().equals(MerchantFeePolicy.STATUS_VALID)
				|| mfp.getStatus().equals(MerchantFeePolicy.STATUS_INVALID)) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"待审核的商户交易资费策略状态不正确!");
		}
		if (mfp.getStatus().equals(MerchantFeePolicy.STATUS_VALID_WAIT_AUTH)) {
			if (mfp.getCreateOperId().compareTo(webInput.getOperId())==0) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
						"商户交易资费策略审核人不可为创建人!");
			}
			// 生效待审核-->无效
			mfp.setStatus(MerchantFeePolicy.STATUS_INVALID);
		} else if (mfp.getStatus().equals(
				MerchantFeePolicy.STATUS_INVALID_WAIT_AUTH)) {
			if (mfp.getAuthOperId().compareTo(webInput.getOperId())==0) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
						"商户交易资费策略审核人不能为申请人!");
			}
			// 无效待审核-->生效
			mfp.setStatus(MerchantFeePolicy.STATUS_VALID);
		}
		mfp.setAuthOperId(webInput.getOperId());
		mfp.setAuthTime(commonDaoImpl.getDatabaseSysTime());
		merchantFeePolicyDaoImpl.update(mfp);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Edit, "审核未通过商户交易折扣/手续费", "商户号："
						+ mfp.getMerchantNo() + "商户机构号："
						+ mfp.getMrchBranchNo());
	}
}